<?php
$action = $_GET['action'];

if (!in_array($action,array('templ','setup'))){
	die('Invalid action value !');
} 

$admin = true;
require_once('auth_req.inc.php');

function update_row($_id, $_template) {
	global $dbh;
	$sth = $dbh->prepare('update msg_template set template=? where t_id=?');
    $sth->execute(array($_template, intval($_id)));	
}

function update_cont($_cont, $_sel, $_action)
{
	global $dbh;
	if ($_action == 0) {
		$sth = $dbh->prepare('update network_map set notify_sms=? where c_id=?');
	}
	else {
		$sth = $dbh->prepare('update network_map set notify_email=? where c_id=?');
	}
    $sth->execute(array(intval($_sel), intval($_cont)));	
}

function insert_addr($_addr, $_action)
{
	global $dbh;
	$sth = $dbh->prepare('insert into msg_setup (notify_type, notify_info) values (?,?)');
    $sth->execute(array(intval($_action), $_addr));	
}

$data = json_decode($HTTP_RAW_POST_DATA, true);

try {
	$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$dbh->beginTransaction();
	
	if ($action == 'templ') {
		foreach ($data as $row) {
			update_row($row['id'], $row['template']);
		}
	}
	else {
		
		$action = $data['action'];
		
		foreach ($data['cont'] as $row) {
			update_cont($row['c_id'], $row['select'], $action);
		}
		
		$sth = $dbh->prepare('delete from msg_setup where notify_type=:type');
        $sth->bindParam(':type', intval($action), PDO::PARAM_INT);
        $sth->execute();
		
		foreach ($data['addr'] as $row) {
			if (!empty($row['address'])) {
				insert_addr($row['address'], $action);
			}				
		}
	}
	$dbh->commit();
}
catch (Exception $e){
	$dbh->rollBack();
}

?>